/***************************************************
File:           LPK_SpawnOnEvent.cs
Authors:        Christopher Onorati
Last Updated:   6/10/2019
Last Version:   2018.3.14

Description:
  This component can be attached to any object to cause
  it to spawn a game object upon receiving an event.

This script is a basic and generic implementation of its 
functionality. It is designed for educational purposes and 
aimed at helping beginners.

Copyright 2018-2019, DigiPen Institute of Technology
***************************************************/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace LPK
{

/**
* CLASS NAME  : LPK_SpawnOnEvent
* DESCRIPTION : Component to spawn a game object on events.
**/
public class LPK_SpawnOnEvent : LPK_Component
{
    /************************************************************************************/

    [Tooltip("What prefab to instantiate upon receiving the event.")]
    [Rename("Prefab")]
    public GameObject m_pPrefabToSpawn;
  
    [Tooltip("Object whose position will be the spawn location.")]
    [Rename("Spawn Transform Object")]
    public Transform m_pTargetSpawnTransformObj;

    [HideInInspector]
    [Tooltip("Time to delay spawn by in seconds.  Useful for respawning a dead character on the same frame it is destroyed or similar functionality.")]
    [Rename("Delay Time")]
    public float m_flDelayTime = 0.0f;

    public bool m_bCopyTargetRotation = false;

    public string m_sNewObjectName;

    public bool m_bAttachToSpawner;
    public bool m_bAttachToSpawnTarget;

    public int m_iSpawnPerEventCount = 1;
    public int  m_iMaxTotalSpawnCount = 0;
    public int m_iMaxAliveAtOnce = 0;

    public Vector3 m_vecOffset;
    public Vector3 m_vecRandomOffsetVariance;
    public Vector3 m_vecRandomAngleVariance;

    public float m_flCooldown = 0.0f;

    [Header("Event Receiving Info")]

    [Tooltip("Which event will trigger this component's action")]
    public LPK_EventObject m_EventTrigger;

    [Header("Event Sending Info")]

    [Tooltip("Event sent when a game object is spawned.")]
    public LPK_EventSendingInfo m_GameObjectSpawnedEvent;

    /************************************************************************************/

    //Whether this component is waiting its cooldown
    protected bool m_bOnCooldown = false;
  
    //Number of objects spawned by this component so far
    protected int m_iSpawnCount = 0;

    protected List<GameObject> m_pActiveList = new List<GameObject>();

    /************************************************************************************/

    protected Transform m_cTransform;

    /**
    * FUNCTION NAME: OnStart
    * DESCRIPTION  : Sets up what event to listen to for object spawning.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    override protected void OnStart()
    {
        m_cTransform = transform;

        if(m_EventTrigger)
            m_EventTrigger.Register(this);

        if (m_pTargetSpawnTransformObj == null)
        {
            m_pTargetSpawnTransformObj = gameObject.transform;

            if(m_bPrintDebug)
                LPK_PrintDebug(this, "Target Transform not found.  Assigning to self.");
        }
    }

    /**
    * FUNCTION NAME: OnEvent
    * DESCRIPTION  : Event validation.
    * INPUTS       : _activator - Game object that activated the event.  Null is all objects.
    * OUTPUTS      : None
    **/
    override public void OnEvent(GameObject _activator)
    {
        if(!ShouldRespondToEvent(_activator))
            return;

        if (m_bOnCooldown)
        {
            if (m_bPrintDebug)
                LPK_PrintDebug(this, "On Cooldown");

            return;
        }

        m_bOnCooldown = true;

        CleanUpList();

        //HACKHACK: Fixes a bug where spawning and destroying an object with the same tag (for example destroing a player via tag player, and then spawning the player) on the same frame.
        //          causes both the dead player and the respawned player to be deleted.  This delays that respawned object from appearing for another frame.
        StartCoroutine(DelaySpawn());

        StartCoroutine(DelayCoolDown());
    }

    /**
    * FUNCTION NAME: DelaySpawn
    * DESCRIPTION  : Forces delay before spawning set object.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    protected IEnumerator DelaySpawn()
    {
        yield return new WaitForSeconds(m_flDelayTime);
        SpawnGameObject();
    }

    /**
    * FUNCTION NAME: SpawnGameObject
    * DESCRIPTION  : Spawn the desired object.  Public so the Unity UI system can interact with this function.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    public virtual void SpawnGameObject()
    {
        //Spawn the objects
        for (int i = 0; i < m_iSpawnPerEventCount; ++i)
        {
            if (m_iMaxTotalSpawnCount == 0 || m_iSpawnCount < m_iMaxTotalSpawnCount)
            {
                //Too many alive objects, but still count the spawn.
                //NOTENOTE: If you want failed spawns not to count, remove the increment line below.
                if(m_pActiveList.Count >= m_iMaxAliveAtOnce && m_iMaxAliveAtOnce != 0)
                {
                    m_iSpawnCount++;
                    return;
                }

                float randX = Random.Range(m_vecOffset.x - m_vecRandomOffsetVariance.x, m_vecOffset.x + m_vecRandomOffsetVariance.x);
                float randY = Random.Range(m_vecOffset.y - m_vecRandomOffsetVariance.y, m_vecOffset.y + m_vecRandomOffsetVariance.y);
                float randZ = Random.Range(m_vecOffset.z - m_vecRandomOffsetVariance.z, m_vecOffset.z + m_vecRandomOffsetVariance.z);

                Vector3 randAngles = new Vector3(Random.Range(-m_vecRandomAngleVariance.x, m_vecRandomAngleVariance.x), Random.Range(-m_vecRandomAngleVariance.y, m_vecRandomAngleVariance.y),
                                                 Random.Range(-m_vecRandomAngleVariance.z, m_vecRandomAngleVariance.z));

                GameObject obj = (GameObject)Instantiate(m_pPrefabToSpawn, m_pTargetSpawnTransformObj.position + new Vector3(randX, randY, randZ), Quaternion.identity);
                Transform objTransform = obj.GetComponent<Transform>();

                if (m_bCopyTargetRotation)
                    objTransform.eulerAngles = m_pTargetSpawnTransformObj.eulerAngles + randAngles;
                else
                    objTransform.eulerAngles = randAngles;

                if (m_bAttachToSpawnTarget)
                    objTransform.SetParent(m_pTargetSpawnTransformObj);

                if (m_bAttachToSpawner)
                    objTransform.SetParent(m_cTransform);

                if (!string.IsNullOrEmpty(m_sNewObjectName))
                    obj.name = m_sNewObjectName;

                if (m_bPrintDebug)
                    LPK_PrintDebug(this, "Game object spawned");

                m_iSpawnCount++;
                m_pActiveList.Add(obj);
            }
        }

        //Dispatch spawn event
        DispatchSpawnEvent();
    }

    /**
    * FUNCTION NAME: DispatchSpawnEvent
    * DESCRIPTION  : Dispatch the spawn event.
    * INPUTS       : obj - Spawned object that may be added to receive the event.
    * OUTPUTS      : None
    **/
    protected void DispatchSpawnEvent()
    {
        if(m_GameObjectSpawnedEvent != null && m_GameObjectSpawnedEvent.m_Event != null)
        {
            if(m_GameObjectSpawnedEvent.m_EventSendingMode == LPK_EventSendingInfo.LPK_EventSendingMode.ALL)
                m_GameObjectSpawnedEvent.m_Event.Dispatch(null);
            else if(m_GameObjectSpawnedEvent.m_EventSendingMode == LPK_EventSendingInfo.LPK_EventSendingMode.OWNER)
                m_GameObjectSpawnedEvent.m_Event.Dispatch(gameObject);

            if (m_bPrintDebug)
                LPK_PrintDebug(this, "Virtual Button Input event dispatched");
        }
    }

    /**
    * FUNCTION NAME: CleanUpList
    * DESCRIPTION  : Remove any nullified objects from the list.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    protected void CleanUpList()
    {
        for (int j = 0; j < m_pActiveList.Count; j++)
        {
            GameObject checkObj = m_pActiveList[j];

            if (checkObj == null)
                m_pActiveList.RemoveAt(j);
        }
    }

    /**
    * FUNCTION NAME: DelayCoolDown
    * DESCRIPTION  : Creates a delay between spawn waves.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    protected IEnumerator DelayCoolDown()
    {
        yield return new WaitForSeconds(m_flCooldown);
        m_bOnCooldown = false;
    }

    /**
    * FUNCTION NAME: OnDestroy
    * DESCRIPTION  : Removes game object from the event queue.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void OnDestroy()
    {
        if(m_EventTrigger != null)
            m_EventTrigger.Unregister(this);
    }
}

#if UNITY_EDITOR

[CustomEditor(typeof(LPK_SpawnOnEvent))]
public class LPK_SpawnOnEventEditor : Editor
{
    SerializedProperty prefabToSpawn;
    SerializedProperty targetSpawnTransformObj;

    SerializedProperty eventTriggers;

    SerializedProperty spawnObjectReceivers;

    /**
    * FUNCTION NAME: OnEnable
    * DESCRIPTION  : Save out serialized classes.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void OnEnable()
    {
        prefabToSpawn = serializedObject.FindProperty("m_pPrefabToSpawn");
        targetSpawnTransformObj = serializedObject.FindProperty("m_pTargetSpawnTransformObj");

        eventTriggers = serializedObject.FindProperty("m_EventTrigger");

        spawnObjectReceivers = serializedObject.FindProperty("m_GameObjectSpawnedEvent");
    }

    /**
    * FUNCTION NAME: OnInspectorGUI
    * DESCRIPTION  : Override GUI for inspector.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    public override void OnInspectorGUI()
    {
        LPK_SpawnOnEvent owner = (LPK_SpawnOnEvent)target;

        LPK_SpawnOnEvent editorOwner = owner.GetComponent<LPK_SpawnOnEvent>();

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel("Script");
        editorOwner = (LPK_SpawnOnEvent)EditorGUILayout.ObjectField(editorOwner, typeof(LPK_SpawnOnEvent), false);
        GUILayout.EndHorizontal();
        EditorGUI.EndDisabledGroup();

        //Undo saving.
        Undo.RecordObject(owner, "Property changes on LPK_SpawnOnEvent");

        //Component properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Component Properties", EditorStyles.boldLabel);

        EditorGUILayout.PropertyField(prefabToSpawn, true);
        EditorGUILayout.PropertyField(targetSpawnTransformObj, true);
        owner.m_bCopyTargetRotation = EditorGUILayout.Toggle(new GUIContent("Copy Target Rotation", "Whether the rotation of TargetSpawnTransformObj should be copied to the spawned object."), owner.m_bCopyTargetRotation);
        owner.m_sNewObjectName = EditorGUILayout.TextField(new GUIContent("Override Name", "Assign this string to the objects spawned as their name."), owner.m_sNewObjectName);
        owner.m_bAttachToSpawner = EditorGUILayout.Toggle(new GUIContent("Assign Parent Spawner", "Parent the created prefab to the spawner object."), owner.m_bAttachToSpawner);
        owner.m_bAttachToSpawnTarget = EditorGUILayout.Toggle(new GUIContent("Assign Parent Target", "Parent the created prefab to the transform spawn location object."), owner.m_bAttachToSpawnTarget);
        owner.m_iSpawnPerEventCount = EditorGUILayout.IntField(new GUIContent("Spawns Per Event", "How many instances of the archetype to spawn everytime an event is received."), owner.m_iSpawnPerEventCount);
        owner.m_iMaxTotalSpawnCount = EditorGUILayout.IntField(new GUIContent("Max Spawns", "Total maximum number of instances this object is allowed to spawn. (0 means no limit)."), owner.m_iMaxTotalSpawnCount);
        owner.m_iMaxAliveAtOnce = EditorGUILayout.IntField(new GUIContent("Max Alive", "Max amount of objects to have active at once.  (0 means no limit)."), owner.m_iMaxAliveAtOnce);
        owner.m_vecOffset = EditorGUILayout.Vector3Field(new GUIContent("Translation Offset", "Translational offset from spawn position."), owner.m_vecOffset);
        owner.m_vecRandomOffsetVariance = EditorGUILayout.Vector3Field(new GUIContent("Translation Offset Variance", "Random translational variance applied to the spawn position. A value of (2, 0, 0) will apply a random offset of -2 to 2 to the X value of the spawn position"), owner.m_vecRandomOffsetVariance);
        owner.m_vecRandomAngleVariance = EditorGUILayout.Vector3Field(new GUIContent("Rotational Offset Variance", "Random angular variance applied to the spawned object's angles."), owner.m_vecRandomAngleVariance);
        owner.m_flCooldown = EditorGUILayout.FloatField(new GUIContent("Cooldown", "Amount of time to wait (in seconds) until an event can trigger another spawn."), owner.m_flCooldown);

        //Events
        EditorGUILayout.PropertyField(eventTriggers, true);
        EditorGUILayout.PropertyField(spawnObjectReceivers, true);

        //Debug properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Debug Properties", EditorStyles.boldLabel);

        owner.m_bPrintDebug = EditorGUILayout.Toggle(new GUIContent("Print Debug Info", "Toggle console debug messages."), owner.m_bPrintDebug);
        owner.m_sLabel = EditorGUILayout.TextField(new GUIContent("Label", "Notes for the user about this component.  This does nothing to the game or build."), owner.m_sLabel);

        //Apply changes.
        serializedObject.ApplyModifiedProperties();
    }
}

#endif  //UNITY_EDITOR

}   //LPK
